﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;

using Gallery.DAL.Repositories;
using Gallery.DAL.Entities;

namespace Gallery.Admin
{
    public partial class Pictures : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["IsAdmin"] == null)
                Response.Redirect("Login.aspx", true);

            if (!IsPostBack)
            {
                LoadData();
                FillAuthorAgeList(ddlAuthorAge);
            }

        }

        private void LoadData()
        {
            grid.DataSource = PictureRepository.FindAll();
            grid.DataBind();
        }

        protected void grid_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            grid.PageIndex = e.NewPageIndex;
            LoadData();
        }

        protected void grid_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                Picture drv = (Picture)e.Row.DataItem;
                HyperLink hlViewImage = (HyperLink)e.Row.FindControl("hlViewImage");
                string imageUrl = ResolveUrl("~/Files/") + drv.PictureId.ToString() + "_" + drv.FileName;
                hlViewImage.NavigateUrl = "javascript:void(0)";
                hlViewImage.Attributes.Add("onclick", string.Format("showImageViewDialog('{0}');", imageUrl));

                if (grid.EditIndex == e.Row.RowIndex)
                {
                    DropDownList ddl = (DropDownList)e.Row.FindControl("ddlMonthGrid");
                    TextBox edt = (TextBox)e.Row.FindControl("txtYearGrid");

                    ddl.SelectedValue = "-1";
                    edt.Text = "";

                    if (drv.DateCreated != null)
                    {
                        ddl.SelectedValue = Convert.ToDateTime(drv.DateCreated).Month.ToString();
                        edt.Text = Convert.ToDateTime(drv.DateCreated).Year.ToString();
                    }

                    ddl = (DropDownList)e.Row.FindControl("ddlAuthorAgeGrid");
                    FillAuthorAgeList(ddl);
                    if (drv.AuthorAge != null)
                    {
                        if (ddl.Items.FindByValue(Convert.ToInt32(drv.AuthorAge).ToString()) != null)
                            ddl.SelectedValue = Convert.ToInt32(drv.AuthorAge).ToString();
                    }
                }
                else
                {
                    ImageButton btnUp = (ImageButton)e.Row.FindControl("btnUp");
                    ImageButton btnDown = (ImageButton)e.Row.FindControl("btnDown");

                    btnUp.Visible = (Convert.ToInt32(drv.SequenceNumber) != 1);
                    btnDown.Visible = (Convert.ToInt32(drv.SequenceNumber) != PictureRepository.MaxNumber());

                    LinkButton deletecommand = (LinkButton)e.Row.Cells[1].Controls[0];
                    deletecommand.OnClientClick = "if (!confirm('Are you sure you want to delete this record?')) return false;";
                }
            }

            /*for (int i = 0; i < e.Row.Cells.Count; i++)
            {
                Control c = e.Row.Cells[i] as Control;
                if (c.Controls.Count > 0)
                {
                    LinkButton l = c.Controls[0] as LinkButton;
                    if (l != null && l.Text.ToLower() == "delete")
                    {
                        e.Row.Cells[i].Attributes.Add("onclick", "return confirm('Are you sure you want to delete this record?');");
                        break;
                    }
                }
            }*/



            // hide Id
            for (int i = 0; i < e.Row.Cells.Count; i++)
            {
                if (i == 2)
                {
                    e.Row.Cells[i].Style.Add("display", "none");
                }
            }

        }

        protected void btnSave_Click(object sender, EventArgs e)
        {

            if (!fuPicture.HasFile)
                return;

            Picture item = new Picture();
            item.PictureName = txtPictureName.Text;
            item.FileName = fuPicture.FileName;
            if (ddlAuthorAge.SelectedValue != "-1")
                item.AuthorAge = Convert.ToInt32(ddlAuthorAge.SelectedValue);
            if ((ddlMonth.SelectedValue != "-1") && (!string.IsNullOrEmpty(txtYear.Text)))
                item.DateCreated = new DateTime(Convert.ToInt32(txtYear.Text), Convert.ToInt32(ddlMonth.SelectedValue), 1);

            //int picId = repo.InsertId(item);
            Guid picId = PictureRepository.InsertId(item);
            fuPicture.SaveAs(Server.MapPath("~/Files/" + picId.ToString() + "_" + fuPicture.FileName));


            LoadData();
        }


        protected void grid_RowEditing(object sender, GridViewEditEventArgs e)
        {
            grid.EditIndex = e.NewEditIndex;
            LoadData();
        }

        protected void grid_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            grid.EditIndex = -1;
            LoadData();
        }

        protected void grid_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {

            String pictureId = (grid.Rows[e.RowIndex].FindControl("lblPictureId") as Label).Text.Trim();
            String fileName = (grid.Rows[e.RowIndex].FindControl("hlViewImage") as HyperLink).Text.Trim();
            String pictureName = (grid.Rows[e.RowIndex].FindControl("txtPictureName") as TextBox).Text.Trim();

            /*String authorAge = (grid.Rows[e.RowIndex].FindControl("txtAuthorAge") as TextBox).Text.Trim();
            String dateCreated = (grid.Rows[e.RowIndex].FindControl("txtDateCreated") as TextBox).Text.Trim(); 
            
            DateTime value;
            if (!DateTime.TryParse(dateCreated, out value))
            {
                String script = " alert('date is invalid, please enter valid date');";
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), Guid.NewGuid().ToString(), script, true);
                return;
            }*/

            string year = (grid.Rows[e.RowIndex].FindControl("txtYearGrid") as TextBox).Text.Trim();
            string month = (grid.Rows[e.RowIndex].FindControl("ddlMonthGrid") as DropDownList).SelectedValue;
            string dateCreated = "";
            if ((!string.IsNullOrEmpty(year)) && (month != "-1"))
            {
                dateCreated = (new DateTime(Convert.ToInt32(year), Convert.ToInt32(month), 1)).ToShortDateString();
            }

            string authorAge = (grid.Rows[e.RowIndex].FindControl("ddlAuthorAgeGrid") as DropDownList).SelectedValue;
            if (authorAge == "-1")
                authorAge = "";
            String[] arr = new String[] { pictureId, fileName, pictureName, authorAge, dateCreated };
            PictureRepository.Update(arr);

            grid.EditIndex = -1;
            LoadData();
        }

        protected void grid_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            String pictureId = (grid.Rows[e.RowIndex].FindControl("lblPictureId") as Label).Text.Trim();
            PictureRepository.Delete(pictureId);

            LoadData();
        }

        protected void grid_Sorting(object sender, GridViewSortEventArgs e)
        {
            
        }

        protected void grid_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            string strArg = e.CommandArgument.ToString();

            if (e.CommandName == "Up")
            {
                PictureRepository.Up(strArg);
                LoadData();
            }
            else if (e.CommandName == "Down")
            {
                PictureRepository.Down(strArg);
                LoadData();
            }
        }

        private void FillAuthorAgeList(DropDownList ddl)
        {
            ddl.Items.Clear();
            ddl.Items.Add(new ListItem("(Author Age)", "-1"));
            for(int i = 6; i <= DateTime.Now.Year - 2000; ++i)
                ddl.Items.Add(new ListItem(i.ToString(), i.ToString()));
        }

    }
}